//
// Created by LINRUI on 2023/1/24.
//

#ifndef KFM_PARALLEL_FOR_WIN_PAR_FOR_H
#define KFM_PARALLEL_FOR_WIN_PAR_FOR_H
#include <cstdio>
#include <vector>
#include <thread>

namespace kfm::par{
    typedef void FuncTypes(); //定义了FuncType这种函数数据类型
    void cut_for(int x, int start, int end,FuncTypes body)
    {
        printf("%d#. \033[3m start:=%d end:=%d setp :=%d thread id: %d \033[0m\n", x, start, end,end-start, std::this_thread::get_id());
        for (int i = start; i < end; i++)
        {
            body();
        }
    }

    void parallel_for(int total, int cut,FuncTypes body)
    {
        int block = total / cut;
        int yu_shu = total - (block * cut);
        int N = (yu_shu > 0) ? cut + 1 : cut;
//        cc << "total := " << total << " cut := " << cut << " block := " << block << " yu_shu := " << yu_shu << " N:= " << N
        printf("\033[3mtotal := %d cut := %d block := %d yu_shu := %d N:= %d\033[0m\n",total,cut,block,yu_shu,N);
        auto threads = new std::thread[N];
        for (int i = 0; i < cut; i++)
        {
            int start_index = i * block;
            int end_index = start_index + block;
            threads[i] = std::thread(cut_for, i+1, start_index, end_index,body);
        }
        if (yu_shu > 0)
        {
            threads[N - 1] = std::thread(cut_for, N, total - yu_shu, total,body);
        }
        for (int i = 0; i < N; i++)
        {
            threads[i].join();
        }

    }


    void par_for(int total, int cut,FuncTypes body)
    {
        parallel_for(total, cut,body);
    }
}

#endif //KFM_PARALLEL_FOR_WIN_PAR_FOR_H
